package com.dflc.controller.DictionaryEntriesController;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dflc.common.CommonConstant;
import com.dflc.entity.po.TBackLoginUser;
import com.dflc.entity.po.TDictionaryEntries;
import com.dflc.entity.rep.HttpResponseEntity;
import com.dflc.mapper.TDictionaryEntriesMapper;
import com.dflc.service.TBackLoginUserService;
import com.dflc.service.TDictionaryEntriesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <数据字典>
 *
 * @author tqx
 * @version 1.0.0.0
 * <p>Title: DictionaryEntriesController </p >
 * <p>Description:  </p >
 * Package: com.dflc.controller.exportContronller
 * Company: 数字涪陵
 * Copyright: Copyright(c) 产品研发与安全部
 * Date: 2023年07月25日 16:54
 */
@RestController
@Slf4j
@RequestMapping("/dictionaryEntriesController")
public class DictionaryEntriesController {


    @Resource
    private TDictionaryEntriesService dictionaryEntriesService;

    @Resource
    private TBackLoginUserService tBackLoginUserService;

    @Resource
    private TDictionaryEntriesMapper tDictionaryEntriesMapper;

    /**
     * 查询数据字典  parent为0，表示查询所有
     *
     * @return HttpResponseEntity
     * @author tqx
     * @date 2025/2/7 11:42
     * Description:[getNewDictionaryEntriesByType ]
     */
    @GetMapping("/getDictionaryEntriesByType/{parent}")
    public HttpResponseEntity getNewDictionaryEntriesByType(@PathVariable("parent") String parent) {

        try {
            List<TDictionaryEntries> list = null;
            LambdaQueryWrapper<TDictionaryEntries> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TDictionaryEntries::getParent, parent);
            queryWrapper.eq(TDictionaryEntries::getState, CommonConstant.StateActive.Active);
            list = dictionaryEntriesService.list(queryWrapper);
            return HttpResponseEntity.success(list);
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }

    }


    /**
     * 新增/修改数据字典
     *
     * @param tDictionaryEntries
     * @return HttpResponseEntity
     * @author tqx
     * @date 2025/2/7 9:42
     * Description:新增/修改数据字典
     */
    @Transactional
    @PostMapping("/addOrUpdateDictionaryEntries")
    public HttpResponseEntity addOrUpdateDictionaryEntries(@RequestBody TDictionaryEntries tDictionaryEntries) {
        try {
            Integer id3 = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(id3);
            if (tBackLoginUser == null) {
                return HttpResponseEntity.error(500, "查询不到当前用户的信息！请检查数据！");
            }
            if (tBackLoginUser.getIsAdmin() != CommonConstant.BackIsAdmin.Yes) {
                //不是超级管理员不能操作
                return HttpResponseEntity.error(500, "没有权限!");
            }
            //先判断当前的是否有下级
            //STAR
            List<TDictionaryEntries> list2 = new ArrayList<>();
            if (!ObjectUtils.isEmpty(tDictionaryEntries.getId())&&"0".equals(tDictionaryEntries.getParent())) {
                //当前数据为顶级时修改时候才需要查询原来的数据和下级
                TDictionaryEntries entries  = dictionaryEntriesService.getById(tDictionaryEntries.getId());
                if (ObjectUtils.isEmpty(entries)){
                    return HttpResponseEntity.error(500, "查询不到当前数据字典的信息！请检查数据！");
                }
                //查询下级
                Map<String, Object> paramsNext = new HashMap<>();
                paramsNext.put("parent",entries.getDictionaryValue());
                paramsNext.put("state",CommonConstant.StateActive.Active);
                list2 = tDictionaryEntriesMapper.findAllByMap(paramsNext);

            }
            //END
            Map<String, Object> params = new HashMap<>();
            params.put("dictionaryValue",tDictionaryEntries.getDictionaryValue());
            params.put("parent",tDictionaryEntries.getParent());
            params.put("state",CommonConstant.StateActive.Active);
            List<TDictionaryEntries> list1 = tDictionaryEntriesMapper.findAllByMap(params);
            if (!ObjectUtils.isEmpty(list1) && !ObjectUtils.isEmpty(tDictionaryEntries.getId())) {
                if (!list1.get(0).getId().equals(tDictionaryEntries.getId())) {
                    return HttpResponseEntity.error(500, "字典值已存在!");
                }
            }else if (!ObjectUtils.isEmpty(list1) && ObjectUtils.isEmpty(tDictionaryEntries.getId())) {
                    return HttpResponseEntity.error(500, "字典值已存在!");
            }
            dictionaryEntriesService.saveOrUpdate(tDictionaryEntries);
            //是修改，并且上面执行后，进行判断是否有下级有下级则进行修改
            for (TDictionaryEntries tDictionaryEntries1 : list2) {
                //有下级则修改成现在的新数据
                tDictionaryEntries1.setParent(tDictionaryEntries.getDictionaryValue());
            }
            dictionaryEntriesService.saveOrUpdateBatch(list2);
            return HttpResponseEntity.success("操作成功!");
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 删除数据字典
     *
     * @param id
     * @return HttpResponseEntity
     * @author tqx
     * @date 2025/2/7 10:30
     * Description: 删除数据字典
     */
    @DeleteMapping("/deleteDictionaryEntries/{id}")
    public HttpResponseEntity deleteDictionaryEntries(@PathVariable("id") String id) {
        try {
            List<String> stringList = Arrays.asList(id.split(","));
            List<Integer> integerList = new ArrayList<>();
            for (String s : stringList) {
                integerList.add(Integer.valueOf(s));
            }
            List<TDictionaryEntries> all = new ArrayList<>();
            List<TDictionaryEntries> tDictionaryEntries = dictionaryEntriesService.list(new QueryWrapper<TDictionaryEntries>().in("id", integerList));
            if (ObjectUtils.isEmpty(tDictionaryEntries)) {
                return HttpResponseEntity.error(500, "数据字典不存在");
            }
            for (TDictionaryEntries tDictionaryEntries1 : tDictionaryEntries) {
                tDictionaryEntries1.setState(CommonConstant.StateActive.Deleted);
                if (tDictionaryEntries1.getParent().equals(CommonConstant.Dictionary.Parent)) {
                    //是字典类型，则还需要删除该类型下的全部字典
                    List<TDictionaryEntries> tDictionaryEntries2 = dictionaryEntriesService.list(new QueryWrapper<TDictionaryEntries>()
                            .eq("parent", tDictionaryEntries1.getDictionaryValue()) .eq("state", CommonConstant.StateActive.Active));
                    if (!ObjectUtils.isEmpty(tDictionaryEntries2)) {
                        return HttpResponseEntity.error(500, "该数据字典下有下级，不能删除！");
                        //有则全部删除
//                        for (TDictionaryEntries tDictionaryEntries3 : tDictionaryEntries2) {
//                            tDictionaryEntries3.setState(CommonConstant.StateActive.Deleted);
//                        }
                    }
                    all.addAll(tDictionaryEntries2);
                }
                all.add(tDictionaryEntries1);
            }
            dictionaryEntriesService.saveOrUpdateBatch(all);
            return HttpResponseEntity.success("操作成功!");
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

}
